﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace XQ.WeChatOfficialAccount.BLL.Common
{
    public class Base64EncodeHelper
    {
        private static string[] letter = { "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l" };
        /// <summary>
        /// 64编码
        /// </summary>
        public static string EncodeBase65(string code)
        {
            string encode = "";
            byte[] bytes = Encoding.UTF8.GetBytes(code);
            try
            {
                Random rd = new Random();
                //转换成base64
                encode = Convert.ToBase64String(bytes);
                //在1、5、9位置插入1位随机串，在3位置插入一位字母
                if (encode.Length > 9)
                {
                    encode = encode.Insert(9, rd.Next(9).ToString());
                }
                if (encode.Length > 5)
                {
                    encode = encode.Insert(5, rd.Next(9).ToString());
                }
                encode = encode.Insert(3, letter[rd.Next(9)]);
                encode = encode.Insert(1, rd.Next(9).ToString());
                //1、2位与3、4位对调
                encode = encode.Substring(2, 2) + encode.Substring(0, 2) + encode.Substring(4);
            }
            catch
            {
            }
            return encode;
        }

        /// <summary>
        /// 64解码
        /// </summary>
        public static string DeCodeBase65(string code)
        {
            string decode = "";
            if (code != string.Empty)
            {
                try
                {
                    //1、2位与3、4位对调
                    code = code.Substring(2, 2) + code.Substring(0, 2) + code.Substring(4);
                    //移除在1、3、5、9位置的随机数
                    code = code.Remove(1, 1);
                    code = code.Remove(3, 1);
                    if (code.Length > 7)
                    {
                        code = code.Remove(5, 1);
                    }
                    if (code.Length > 10)
                    {
                        code = code.Remove(9, 1);
                    }
                    //还原base64
                    byte[] bytes = Convert.FromBase64String(code);
                    decode = Encoding.UTF8.GetString(bytes);
                }
                catch
                {
                }
            }
            return decode;
        }

    }
}
